#!/bin/bash
# Nginx 自动配置脚本
# 在服务器上运行: bash setup-nginx.sh

set -e

echo "================================"
echo "Nginx Setup for OY Promotion"
echo "================================"
echo ""

# 检查是否为 root
if [ "$EUID" -ne 0 ]; then 
    echo "请使用 root 用户运行此脚本"
    exit 1
fi

# 1. 安装 Nginx
echo "[1/5] 检查 Nginx..."
if ! command -v nginx &> /dev/null; then
    echo "Nginx 未安装，正在安装..."
    apt update
    apt install nginx -y
    echo "✅ Nginx 安装完成"
else
    echo "✅ Nginx 已安装"
fi

# 2. 创建部署目录
echo ""
echo "[2/5] 创建部署目录..."
mkdir -p /var/www/oy-promotion
chown -R www-data:www-data /var/www/oy-promotion 2>&1 || chown -R nginx:nginx /var/www/oy-promotion
chmod -R 755 /var/www/oy-promotion
echo "✅ 目录创建完成: /var/www/oy-promotion"

# 3. 创建 Nginx 配置
echo ""
echo "[3/5] 配置 Nginx..."
cat > /etc/nginx/sites-available/oy-promotion << 'EOF'
server {
    listen 80;
    server_name _;
    
    root /var/www/oy-promotion;
    index index.html;
    
    # 支持 SPA 路由
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    # API 代理（如果需要）
    location /api/ {
        proxy_pass http://localhost:8000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    # 静态资源缓存
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # Gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_min_length 1000;
}
EOF
echo "✅ 配置文件创建完成"

# 4. 启用站点
echo ""
echo "[4/5] 启用站点..."
ln -sf /etc/nginx/sites-available/oy-promotion /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
echo "✅ 站点已启用"

# 5. 测试并重启 Nginx
echo ""
echo "[5/5] 测试并重启 Nginx..."
nginx -t
systemctl restart nginx
systemctl enable nginx
echo "✅ Nginx 已重启"

echo ""
echo "================================"
echo "✅ 配置完成！"
echo "================================"
echo ""
echo "访问地址: http://$(hostname -I | awk '{print $1}')"
echo ""
echo "目录结构:"
echo "  配置文件: /etc/nginx/sites-available/oy-promotion"
echo "  网站目录: /var/www/oy-promotion"
echo ""
echo "常用命令:"
echo "  重启 Nginx: systemctl restart nginx"
echo "  查看状态: systemctl status nginx"
echo "  查看日志: tail -f /var/log/nginx/error.log"
echo ""
